package com.eclipse.e20200201_多线程同步.多线程练习;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.eclipse.e20200201_多线程同步.com.qf.app1.JDBCUtils;

public class Test1 {

	public static void main(String[] args) {
		Task1 task1 = new Task1("g:/table1.txt");
		task1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				System.out.println(t.getName() + "出现了异常：" + e.getClass());
			}
		});
		task1.start();

		Task2 task2 = new Task2("g:/table.txt");
		Thread thread = new Thread(task2);
		thread.start();

	}

}


class Task {
	private String fileName;

	public Task(String fileName) {
		this.fileName = fileName;
	}

	public String getFileName() {
		return this.fileName;
	}

}

class Task2 extends Task implements Runnable {

	public Task2(String fileName) {
		super(fileName);
	}

	public void run() {
		BufferedReader bf = null;
		try {
			bf = new BufferedReader(new FileReader(getFileName()));

			String line = null;
			while (line != null) {
				line = bf.readLine();
				System.out.println(line);
				Thread.currentThread().sleep(1000);
			}
		} catch (FileNotFoundException ex) {
			System.out.println(getFileName() + " 找不到");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bf != null) {
				try {
					bf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class Task1 extends Thread {
	private String fileName;

	public Task1(String fileName) {
		this.fileName = fileName;
	}

	public void run() {
		FileWriter writer = null;
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;

		try {
			writer = new FileWriter(fileName);
			connection = JDBCUtils.getConnection();

			statement = connection.prepareStatement("select * from student");

			resultSet = statement.executeQuery();
			String line = null;
			while (resultSet.next()) {
				line = resultSet.getInt("student_id") + "," + resultSet.getString("name");
				writer.append(line);
			}
		} catch (IOException ex) {
			System.out.println("IO 异常。。。。。。。。");

		} catch (SQLException ex) {
			System.out.println("SQL 异常。。。。。。。。");
		} finally {
			JDBCUtils.closeResourec(connection, statement, resultSet);
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
